package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;

public class ServerThread implements Runnable {
    private Socket accept;
    BufferedReader br = null;

    public ServerThread(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        // 3、从socket通信管道中得到一个字节输入流。
        try {
            InputStream is = accept.getInputStream();
            // 4、把原始的字节输入流包装成高效的输入流
            InputStreamReader isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            // 5、使用数据输入流读取客户端发送过来的消息
            while (true) {
                String s = br.readLine();
                if (s == null) {
                    Server.list.remove(accept);
                    break;
                }
                System.out.println("服务端发送的信息是:" + s);
                for (Socket socket : Server.list) {
                    if (socket != accept) {
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        bw.write(s);
                        bw.newLine();
                        bw.flush();
                    }
                }
            }
            // 6、释放资源

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            try {
                accept.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
